package com.zb.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Objects;

/**
 * @author: zhaobin
 * @date: 2023/12/23 15:14
 * @Description:
 */
public class ServerSocketChannelDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 定义端口
        int port = 9999;

        // 创建缓冲区，并存入数据
        String str = "Hello World!";
        ByteBuffer buf = ByteBuffer.wrap(str.getBytes());

        // 创建ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // 绑定端口
        ssc.bind(new InetSocketAddress(port));

        // 设置非阻塞模式
        ssc.configureBlocking(false);
        System.out.println(ssc.isBlocking());

        // 监听是否有新的链接传入
        while (true) {
            SocketChannel accept = ssc.accept();
            if (Objects.isNull(accept)) {
                System.out.println("Waiting for connections:" + accept);
                Thread.sleep(2000);
            } else {
                // 有连接的情况
                System.out.println("当前连接：" + accept.getRemoteAddress());
                buf.rewind(); // 指针0
                accept.write(buf);
                accept.close();
            }
        }
    }
}

